package com.example.yichuangyun.ui.activity.index;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityMyEventBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.index.DaiBanDataModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.DaiBanEventAdapter;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 我的待办事项
 */
public class MyEventActivity extends BaseActivity<ActivityMyEventBinding, BaseViewModel> {

    private String currentSelectDate;
    private DaiBanEventAdapter adapter;
    private List<DaiBanDataModel.RecordsBean> daiBanData = new ArrayList<>();
    private int page = 1;
    /**
     * 拨打的电话号码
     */
    private String mTelNumber;
    private String businessId;
    private String clientName;
    private boolean isCalling;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.my_to_do));
        currentSelectDate = DateUtil.getCurrentDay();
        binding.tvDate.setText(DateUtil.getCurrentMonthC());
        initMonthRequest(DateUtil.getCurrentDay());
        getBacklogSchedule(currentSelectDate, page);
    }

    /**
     * 待办事项
     */
    private void getBacklogSchedule(String currentSelectDate, int page) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("trackDateNext", currentSelectDate);
            requestDate.put("current", page);
            requestDate.put("size", Constant.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBacklogSchedule(requestBody), new MyObserver<HttpRespond<DaiBanDataModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<DaiBanDataModel> daiBanDataModelHttpRespond) {
                if (Constant.SUCCESS == daiBanDataModelHttpRespond.code) {
                    if (daiBanDataModelHttpRespond.data != null && daiBanDataModelHttpRespond.data.getRecords() != null) {
                        List<DaiBanDataModel.RecordsBean> records = daiBanDataModelHttpRespond.data.getRecords();
                        if (records.size() < Constant.SUCCESS) {
                            binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }
                        if (page == 1) {
                            daiBanData = records;
                            adapter.onRefresh(daiBanData);
                            binding.smartRefreshLayout.finishRefresh();
                        } else {
                            adapter.addData(records);
                            binding.smartRefreshLayout.finishLoadMore();
                        }
                    }
                }
            }
        });
    }

    private void initMonthRequest(String trackDateNext) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("trackDateNextStart", trackDateNext);
            requestDate.put("trackDateNextEnd", DateUtil.getLastDayOfChooseMonth(trackDateNext));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getMonthBlockLog(requestBody), new MyObserver<HttpRespond<List<String>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<String>> listHttpRespond) {
                if (listHttpRespond.code == Constant.SUCCESS) {
                    if (listHttpRespond.data != null && listHttpRespond.data.size() > 0) {
                        List<String> list = listHttpRespond.data;
                        Map<String, Calendar> map = new HashMap<>();
                        for (String s : list) {
                            Calendar calendar = new Calendar();
                            calendar.setYear(Integer.parseInt(s.substring(0, 4)));
                            calendar.setMonth(Integer.parseInt(s.substring(5, 7)));
                            calendar.setDay(Integer.parseInt(s.substring(8, 10)));
                            map.put(calendar.toString(), calendar);
                        }
                        binding.calendarView.setSchemeDate(map);
                    }
                }
            }
        });
    }

    @Override
    public void initCtrl() {
        adapter = new DaiBanEventAdapter(context, daiBanData);
        binding.recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initClick() {
        // 日历
        binding.calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                String month;
                String day;
                String year = calendar.getYear() + "";
                month = calendar.getMonth() < 10 ? "0" + calendar.getMonth() : String.valueOf(calendar.getMonth());
                day = calendar.getDay() < 10 ? "0" + calendar.getDay() : String.valueOf(calendar.getDay());
                currentSelectDate = getString(R.string.year_month_day, year, month, day);
                binding.tvDate.setText(getString(R.string.year_month, year, month));
                page = 1;
                getBacklogSchedule(currentSelectDate, page);
            }
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getBacklogSchedule(currentSelectDate, page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getBacklogSchedule(currentSelectDate, page);
            }
        });

        adapter.setOnCallListener(model -> {
            mTelNumber = model.getTelNumber();
            clientName = model.getUserName();
            businessId = model.getId();
            checkCallNum();
        });
    }

    private void initDialog(String title, String content) {
        MyDialog myDialog = new MyDialog(this) {
            @Override
            public void rightClick() {
                if (!XXPermissions.isGrantedPermission(context, Permission.CALL_PHONE)) {
                    XXPermissions.with(context)
                            .permission(Permission.CALL_PHONE)
                            .request((permissions, all) -> {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_CALL);
                                intent.setData(Uri.parse("tel:" + mTelNumber));
                                startActivity(intent);
                            });
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + mTelNumber));
                    startActivity(intent);
                }
                isCalling = true;
            }
        };
        myDialog.setText(title, content);
        myDialog.showDialog();
    }

    /**
     * 获取拨打电话次数
     */
    private void checkCallNum() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkPhone(mTelNumber), new MyObserver<HttpRespond<Boolean>>() {
            @Override
            protected void onSuccess(HttpRespond<Boolean> booleanHttpRespond) {
                if (Constant.SUCCESS == booleanHttpRespond.code) {
                    if (booleanHttpRespond.data) {
//                                initDialog(1, getString(R.string.call_fail));
                        ToastHelper.show(getString(R.string.call_fail));
                    } else {
                        initDialog(mTelNumber, getString(R.string.confirm_call_num));
                    }
                }
            }
        });
    }
}